package com.bobbygu.bobbyapp.function.upload

import android.graphics.Bitmap
import android.util.Log
import android.widget.Toast
import com.bobbygu.bobbyapp.base.MyApplication
import com.bobbygu.bobbyapp.network.HttpAction
import com.bobbygu.bobbyapp.utils.FileUtils
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File
import java.util.*

/**
 *
 * # time:   2017/10/24 12:59
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since
 */
class UploadModel : UploadContract.Model() {
    override fun uploadFile(bitmap: Bitmap) {
        post(HttpAction.upload, { jsonObject ->
            Log.d("UploadModel", "json:" + jsonObject.toJSONString())
        }, { errMsg, _ ->
            Toast.makeText(MyApplication.getInstance(), errMsg, Toast.LENGTH_SHORT).show()
        })
    }

    override fun uploadFile(filePath: String?) {
        Log.d("UploadModel", "filePath=" + filePath)
        val file = File(filePath)
        if (file.exists()) {
            Log.d("UploadModel", "文件存在")
        } else {
            Log.d("UploadModel", "文件不存在")
        }
        // 添加描述
        val descriptionString = "hello, 这是文件描述"
        val description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString)
        // create a map of data to pass along
        val tokenBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val map = HashMap<String, RequestBody>()
        map.put("ImgData", tokenBody)
        postUpload(description, map, { _ ->
            //            Log.d("LoginModel", "json:" + jsonObject.toJSONString())
            Toast.makeText(MyApplication.getInstance(), "上传成功", Toast.LENGTH_SHORT).show()
        }, { errMsg, _ ->
            Toast.makeText(MyApplication.getInstance(), errMsg, Toast.LENGTH_SHORT).show()
        })
    }

    override fun getImg() {
        val map = HashMap<String, String>()
        map.put("Name", "ImgData")
        postRB(HttpAction.GetImg, map, { responseBody ->
            Log.d("UploadModel", "responseBody:" + responseBody)
            val bs = responseBody.byteStream()
            val fileName = "gentoken.jpg"
            val bytes = FileUtils.getBytes(bs)
            viewModel.returnImgPath(FileUtils.writeTempData(MyApplication.getInstance(), bytes, fileName))
        }, { errMsg, _ ->
            Toast.makeText(MyApplication.getInstance(), errMsg, Toast.LENGTH_SHORT).show()
        })
    }
}